package com.ly.dingTalk.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ly.dingTalk.bean.message.DtEventMessage;
import com.ly.dingTalk.bean.message.DtEventOutMessage;
import com.ly.dingTalk.configuration.DtConfiguration;
import com.ly.dingTalk.dingcon.DtService;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/event/callback/{appKey}")
@Slf4j
public class DtEventController {

    @PostMapping(produces = "application/json; charset=UTF-8")
    public String post(@PathVariable String appKey,
                    @RequestBody String requestBody,
                    @RequestParam("signature") String signature,
                    @RequestParam("timestamp") String timestamp,
                    @RequestParam("nonce") String nonce) {
        log.info("接收回调请求：appKey:{} signature:{}, timestamp:{}, nonce:{}, requestBody:{}", appKey, signature, timestamp, nonce, requestBody);

        final DtService dtService = DtConfiguration.getDtService(appKey);
        DtEventMessage inMessage = DtEventMessage.fromEncryptedJson(requestBody, dtService.getDtConfigStorage(), timestamp, nonce, signature);
        log.info("消息解密后内容为：{} ", inMessage);
        Boolean outMessage = this.route(appKey, inMessage);
        log.info("应用消息处理结果: {}", outMessage);

        outMessage = this.route(dtService, inMessage);
        log.info("统一消息处理结果: {}", outMessage);

        DtEventOutMessage res = DtEventOutMessage.toEncrypted(dtService.getDtConfigStorage(), outMessage);
        log.info("组装回复信息：{}", res);
        return res.toEncryptedJson();
    }

    /**
     * 获取到具体的DtMessageRouter来处理消息
     * @param appKey
     * @param message
     * @return
     */
    private Boolean route(String appKey, DtEventMessage message) {
        try {
            return DtConfiguration.getRouters().get(appKey).route(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }

    /**
     * 直接使用统一的DtMessageRouter来处理消息
     * @param dtService
     * @param message
     * @return
     */
    private Boolean route(DtService dtService, DtEventMessage message) {
        try {
            return DtConfiguration.getRouter().route(dtService, message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return false;
    }


}
